* This file produces the Figures in the main text in the paper (Figures 1 - 3), 2 figures from Appendix A (Figures A2 and A3) and the Appendix C figures (Figures C1 and C2)

use "$saveddata/data_complete_withcosts.dta", clear

set more off
		* Collapse to correct level
		collapse (count) freq = aeattenddisp (mean) admit death30 d_age, by(bin)

		* Now do analysis...
		egen sumfreq = sum(freq)
		gen pfreq = freq/sumfreq
		drop sumfreq

		lab var pfreq "Proportion of patients"
		lab var bin "Exit time (10 min intervals)"
		compress
		
		gen plotfreq = freq / 1000
		format %9.0fc plotfreq	
		gen plotadmit = admit*100


		** ANALYSIS HERE
		
		* bin polynomial variables
	forv x = 1/15 {
		gen bin`x' = bin^`x'
		}
		

	* parameters
	local porder = 10
	local start = 180
	local end = 240


* waiting times - find end point
local sumdiff = 999
while abs(`sumdiff')>0.01 {
	
	* drop variables created in loop
	cap drop pfreq_cf freq_cf diff
	
	* update end point
	local end = `end' + 10	
	
	* compute counterfactual
	qui reg pfreq bin1-bin`porder' if bin<`start' | bin>`end'
	predict pfreq_cf, xb
	qui reg freq bin1-bin`porder' if bin<`start' | bin>`end'
	predict freq_cf, xb

	* check difference in mass
	gen diff = pfreq - pfreq_cf 
	qui su diff if bin>`start' | bin<`end'
	local sumdiff = r(sum)
		
	* display end point
	di "End point: `end'"
	}
drop diff

* Figure 1
format %9.0fc plotfreq
scatter plotfreq bin if bin<=600, msymbol(o) connect(line) lcolor(black) mcolor(black) ///
	xtick(0(30)600) xmtick(0(10)600) xlab(0(60)600) graphregion(color(white)) ///
	ytitle("Number of patients (000s)") xtit("Waiting time (mins)") xline(240, lcolor(red) lpattern(shortdash))
graph export "$results/fig1.pdf", as(pdf) replace	

* Figure 2
gen temp = 2500 if bin>=`start' & bin<=`end'
gen plotfreq_cf = freq_cf / 1000
format %9.0fc plotfreq_cf temp
twoway area temp bin if bin<=600, color(gs10) || scatter plotfreq bin if bin<=600, msymbol(o) connect(line) lcolor(black) mcolor(black) || ///
	line plotfreq_cf bin if bin<=600, xlab(0(60)600) lpattern(dash) lcolor(black) || pci 0 240 0.2500 240, lcolor(red) lpattern(shortdash) ///
	xtick(0(30)600) xmtick(0(10)600) graphregion(color(white)) ///
	legend(lab(2 "Observed data") lab(3 "Estimated counterfactual") order(2 3)) ///
	ytitle("Number of patients (000s)") xtit("Waiting time (mins)")
graph export "$results/fig2.pdf", as(pdf) replace	




* Make Figure 3 
scatter plotadmit bin if bin<=600, msymbol(o) connect(line) lcolor(black) mcolor(black) ///
	xtick(0(30)600) xmtick(0(10)600) xlab(0(60)600) graphregion(color(white)) ///
	ytitle("Admission probability (%)") xtit("Waiting time (mins)") xline(240, lcolor(red) lpattern(shortdash))
graph export "$results/fig3.pdf", as(pdf) replace


	* waiting times - compute effects, need these weights to create CAC for other outcomes
	gen wait = freq*bin 

	gen wait_cf = freq_cf*bin 
	gen wait_diff = wait_cf - wait

	su wait_diff
	local saving = r(sum)
	su freq
	local patients = r(sum)/2
	su wait_cf
	local totalwait = r(sum)/2
	su wait_diff if bin>=`start' & bin<=`end'
	local saving_int = r(sum)
	su wait_cf if bin>=`start' & bin<=`end'
	local totalwait_int = r(sum)/2
	su freq if bin>=`start' & bin<=`end'
	local patients_int = r(sum)/2
	local savingpp = round(`saving'/`patients',1)
	local savingpc = round(`saving'/`totalwait',0.01)
	local savingpp_int = round(`saving_int'/`patients_int',1)
	local savingpc_int = round(`saving_int'/`totalwait_int',0.01)
	
* These gives you the wait time results reported on page 28
	
	di "Total waiting time saving (mins per patient): " `savingpp'
	di "Total waiting time saving (% of c.f. total): " `savingpc'
	di "Total waiting time saving in distorted window (mins per patient): " `savingpp_int'
	di "Total waiting time saving in disorted window (% of c.f. total): " `savingpc_int'

* other outcomes - parameters and inputs to later calculations
*qui reg freq bin1-bin`porder' if bin<`start' | bin>`end'
*predict freq_cf, xb
gen freq_diff = freq_cf - freq 
egen sumfreq_pre_cf = sum(freq_cf) if bin>`start' & bin<=240
egen sumfreq_post_diff = sum(freq_diff) if bin>240 & bin<=`end'
egen sumfreq_pre = sum(freq) if bin>`start' & bin<=240
gen w_pre = freq_cf/sumfreq_pre_cf
gen w_post_diff = freq_diff/sumfreq_post_diff
gen w = freq/sumfreq_pre
gen nonmover_pre = sumfreq_pre_cf/sumfreq_pre
drop *cf

* new end point
local t = 260

* other outcomes - compute counterfactuals and selection-only counterfactuals
foreach var of varlist admit death30 d_age{

	* counterfactual outcomes
	qui reg `var' bin1-bin`porder' if bin<`start' | bin>`t'
	
	predict `var'_cf, xb
	
	* non-movers: pre-target counterfactual average outcome 
	qui egen `var'_pre_cf = sum(`var'_cf*w_pre)
		
	* movers: post-target counterfactual average outcome (weighted by mover proportions)
	qui egen `var'_post_cf = sum(`var'_cf*w_post_diff)

	* selection-only counterfactual
	qui gen `var'_selection = nonmover_pre*`var'_pre_cf + (1-nonmover_pre)*`var'_post_cf
	
	* observed outcome (averaged over pre period)
	qui egen `var'_observed = sum(`var'*w)
	}
	
* For graphs - put variables into percentages
foreach i in admit death30{
	replace `i' = `i' * 100
	replace `i'_cf = `i'_cf * 100
}
	
* Make Appendix A Figure A2

	cap drop temp

	su admit
	gen temp = r(max) if bin>=`start' & bin<=`t'
	twoway area temp bin if bin<=600, color(gs10) || scatter admit bin if bin<=600, msymbol(o) connect(line) lcolor(black) mcolor(black) || ///
		line admit_cf bin if bin<=600, xlab(0(60)600) lpattern(dash) lcolor(black) || pci 0 240 `r(max)' 240, lcolor(red) lpattern(shortdash) ///
		xtick(0(30)600) xmtick(0(10)600) graphregion(color(white)) ///
		legend(lab(2 "Observed data") lab(3 "Estimated counterfactual") order(2 3)) ///
		ytitle("Admission probability (%)") xtit("Waiting time (mins)")
	graph export "$results/figA2.pdf", as(pdf) replace
	

* Make Appendix A Figure A3

	cap drop temp1 temp2 obs cf_pre cf_post cf_select
	su death30
	gen temp1 = r(max) if bin>=`start' & bin<=240
	gen temp2 = r(max) if bin>=240 & bin<=`end'
	su death30_observed if bin>`start' & bin<=240
	gen obs = r(mean) * 100
	su death30_pre_cf if bin>`start' & bin<=240 
	gen cf_pre = r(mean) * 100
	su death30_post_cf if bin>240 & bin<=400
	gen cf_post = r(mean) * 100
	su death30_selection
	gen cf_select = r(mean) * 100
	su death30
	twoway area temp1 bin if bin<=600, color(gs12) || area temp2 bin if bin<=600, color(gs10) || ///
		scatter death30 bin if bin<=600, msymbol(o) connect(line) lcolor(black) mcolor(black) || ///
		line death30_cf bin if bin<=600, xlab(0(60)600) lpattern(dash) lcolor(black) || ///
		pci 0 240 `r(max)' 240, lcolor(red) lpattern(shortdash) || ///
		line obs bin if bin>=`start' & bin<=240, lcolor(black) lwidth(thick) || ///
		line cf_select bin if bin>=`start' & bin<=240, lcolor(black) lpattern(dash) lwidth(thick) || ///
		line cf_pre bin if bin>=`start' & bin<=240, lcolor(black) lpattern(shortdash) || line cf_post bin if bin>=240 & bin<=`end', lcolor(black) lpattern(shortdash) ///
		xtick(0(30)600) xmtick(0(10)600) graphregion(color(white)) ylab(1(1)7) ///
		legend(lab(3 "Observed") lab(4 "Counterfactual") order(3 4) rows(1)) ///
		ytitle("30-day mortality (%)") xtit("Wait time (mins)")  ///
		text(3.1 400 "E[y{subscript:0} | w{superscript:*} < w{subscript:0} < w{superscript:+}]", place(e) size(small)) ///
		text(1.5 180 "E[y{subscript:0} | w{superscript:-} < w{subscript:0} < w{superscript:*}]", place(w) size(small)) ///
		text(2.15 180 "CAC: E[y{subscript:0} | w{superscript:-} < w{subscript:1} < w{superscript:*}]", place(w) size(small)) ///
		text(1.85 180 "Obs.: E[y{subscript:1} | w{superscript:-} < w{subscript:1} < w{superscript:*}]", place(w) size(small)) 
	graph export "$results/figA3.pdf", as(pdf) replace
	
 
** Make Appendix Figure C1

cap drop temp1 temp2 obs cf_pre cf_post cf_select
	su admit
	gen temp1 = r(max) if bin>=`start' & bin<=240
	gen temp2 = r(max) if bin>=240 & bin<=`end'
	su admit_observed if bin>`start' & bin<=240
	gen obs = r(mean) * 100
	su admit_pre_cf if bin>`start' & bin<=240 
	gen cf_pre = r(mean) * 100
	su admit_post_cf if bin>240 & bin<=400
	gen cf_post = r(mean) * 100
	su admit_selection
	gen cf_select = r(mean) * 100
	su admit
	twoway area temp1 bin if bin<=600, color(gs12) || area temp2 bin if bin<=600, color(gs10) || ///
		scatter admit bin if bin<=600, msymbol(o) connect(line) lcolor(black) mcolor(black) || ///
		line admit_cf bin if bin<=600, xlab(0(60)600) lpattern(dash) lcolor(black) || ///
		pci 0 240 `r(max)' 240, lcolor(red) lpattern(shortdash) || ///
		line obs bin if bin>=`start' & bin<=240, lcolor(black) lwidth(thick) || ///
		line cf_select bin if bin>=`start' & bin<=240, lcolor(black) lpattern(dash) lwidth(thick) || ///
		line cf_pre bin if bin>=`start' & bin<=240, lcolor(black) lpattern(shortdash) || line cf_post bin if bin>=240 & bin<=`end', lcolor(black) lpattern(shortdash) ///
		xtick(0(30)600) xmtick(0(10)600) graphregion(color(white)) ///
		legend(lab(3 "Observed data") lab(4 "Estimated counterfactual") order(3 4)) ///
		ytitle("Admission probability (%)") xtit("Wait time (mins)") ///
		text(48.5 400 "E[y{subscript:0} | w{superscript:*} < w{subscript:0} < w{superscript:+}]", place(e) size(small)) ///
		text(29.7 180 "E[y{subscript:0} | w{superscript:-} < w{subscript:0} < w{superscript:*}]", place(w) size(small)) ///
		text(37.4 180 "CAC: E[y{subscript:0} | w{superscript:-} < w{subscript:1} < w{superscript:*}]", place(w) size(small)) ///
		text(42.5 180 "Obs.: E[y{subscript:1} | w{superscript:-} < w{subscript:1} < w{superscript:*}]", place(w) size(small))
	graph export "$results/figC1.pdf", as(pdf) replace
	
* Make Appendix C Figure C2

 
	cap drop temp1 temp2 obs cf_pre cf_post cf_select
	su d_age
	gen temp1 = r(max) if bin>=`start' & bin<=240
	gen temp2 = r(max) if bin>=240 & bin<=`end'
	su d_age_observed if bin>`start' & bin<=240
	gen obs = r(mean) 
	su d_age_pre_cf if bin>`start' & bin<=240 
	gen cf_pre = r(mean) 
	su d_age_post_cf if bin>240 & bin<=400
	gen cf_post = r(mean) 
	su d_age_selection
	gen cf_select = r(mean) 
	su d_age
	twoway area temp1 bin if bin<=600, color(gs12) || area temp2 bin if bin<=600, color(gs10) || ///
		scatter d_age bin if bin<=600, msymbol(o) connect(line) lcolor(black) mcolor(black) || ///
		line d_age_cf bin if bin<=600, xlab(0(60)600) lpattern(dash) lcolor(black) || ///
		pci 0 240 `r(max)' 240, lcolor(red) lpattern(shortdash) || ///
		line obs bin if bin>=`start' & bin<=240, lcolor(black) lwidth(thick) || ///
		line cf_select bin if bin>=`start' & bin<=240, lcolor(black) lpattern(dash) lwidth(thick) || ///
		line cf_pre bin if bin>=`start' & bin<=240, lcolor(black) lpattern(shortdash) || line cf_post bin if bin>=240 & bin<=`end', lcolor(black) lpattern(shortdash) ///
		xtick(0(30)600) xmtick(0(10)600) graphregion(color(white)) ///
		legend(lab(3 "Observed data") lab(4 "Estimated counterfactual") order(3 4)) //////
		ytitle("Age") xtit("Wait time (mins)")  ///
		text(50.7 400 "E[y{subscript:0} | w{superscript:*} < w{subscript:0} < w{superscript:+}]", place(e) size(small)) ///
		text(43.3 180 "E[y{subscript:0} | w{superscript:-} < w{subscript:0} < w{superscript:*}]", place(w) size(small)) ///
		text(46.3 180 "CAC: E[y{subscript:0} | w{superscript:-} < w{subscript:1} < w{superscript:*}]", place(w) size(small)) ///
		text(49.3 180 "Obs.: E[y{subscript:1} | w{superscript:-} < w{subscript:1} < w{superscript:*}]", place(w) size(small)) 
		graph export "$results/figC2.pdf", as(pdf) replace

	
